import HandleBtn from '@/components/HandleBar/btn';
import { ProTable, type ProColumns } from '@/components/Pro';
import {
  historyDataControllerBoxHistoryData,
  historyDataControllerHistoryDataExport as exportDataReport,
} from '@/services/ess/historicalData';
import { downloadFetch } from '@/utils/downloadFile';
import { Link, useIntl } from '@umijs/max';
import { message } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import React, { useEffect, useState } from 'react';

interface Props {
  tabIndex?: string;
  deviceCode?: string;
  deviceType?: string;
  areaId?: string;
  selectedKeys?: string[];
}

const BatteryBoxDetails: React.FC<Props> = ({ deviceCode, deviceType, areaId, selectedKeys }) => {
  const intl = useIntl(); // 获取国际化实例
  const [data, setData] = useState<API.BoxPageDataDTO[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [params, setParams] = useState({
    current: 1,
    pageSize: 20,
    startDate: dayjs().startOf('day').format('YYYY-MM-DDTHH:mm:ss'),
    endDate: dayjs().format('YYYY-MM-DDTHH:mm:ss'),
  });
  const [selectedColumns, setSelectedColumns] = useState<string[]>([]);
  const columns: ProColumns<any>[] = [
    {
      title: intl.formatMessage({ id: 'data.s/N' }), // 使用国际化字段
      key: 'index',
      valueType: 'index',
      width: 60,
      dataIndex: 'pageIndex',
    },
    {
      title: intl.formatMessage({ id: 'data.time' }), // 时间
      dataIndex: 'time',
      key: 'time',
      valueType: 'dateTimeRange',
      width: 200,
      initialValue: [dayjs().startOf('day'), dayjs()],
      render: (_, record) => {
        return <span>{record.time}</span>;
      },
      search: {
        transform: (value) => {
          return {
            startDate: value ? dayjs(value[0]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
            endDate: value ? dayjs(value[1]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
          };
        },
      },
      fieldProps: {
        onCalendarChange: (dates: [Dayjs, Dayjs]) => {
          if (dates && dates.length === 2) {
            const [start, end] = dates;
            if (dayjs(end).diff(start, 'day') > 31) {
              message.warning(intl.formatMessage({ id: 'data.sDays' }));
            }
          }
        },
        disabledDate: (current: Dayjs | null) => {
          return current && current > dayjs().endOf('day');
        },
      },
    },
    // {
    //   title: intl.formatMessage({ id: 'data.faults' }), // 故障数量
    //   dataIndex: 'faultCount',
    //   key: 'faultCount',
    //   hideInSearch: true,
    //   width: 150,
    // },
    {
      title: intl.formatMessage({ id: 'data.soc' }), // SOC
      dataIndex: 'soc',
      key: 'soc',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.dailyCharge' }), // 当日充电量
      dataIndex: 'dailyCharge',
      key: 'dailyCharge',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.dailyDischarge' }), // 当日放电量
      dataIndex: 'dailyDischarge',
      key: 'dailyDischarge',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.totalCharge' }), // 累计充电量
      dataIndex: 'totalCharge',
      key: 'totalCharge',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.totalDischarge' }), // 累计放电量
      dataIndex: 'totalDischarge',
      key: 'totalDischarge',
      hideInSearch: true,
      width: 150,
    },
  ];

  const fetchData = async (params: {
    current: number;
    pageSize: number;
    startDate: string;
    endDate: string;
  }) => {
    setLoading(true);
    const response = await historyDataControllerBoxHistoryData({
      current: params.current,
      pageSize: params.pageSize,
      startDate: params.startDate,
      endDate: params.endDate,
      deviceCode,
      deviceType,
      areaId,
    });

    if (response.success && response.data && response.data?.records) {
      setData(
        response.data.records.map((record, index) => ({
          pageIndex: (params.current - 1) * params.pageSize + index + 1,
          time: record.collectTime,
          faultCount: record.faultNum,
          soc: record.soc,
          dailyCharge: record.todayChargedEnergy,
          dailyDischarge: record.todayDischargedEnergy,
          totalCharge: record.chargedEnergy,
          totalDischarge: record.dischargedEnergy,
        })),
      );
      // @ts-ignore
      setTotal(response.data.total);
    } else {
      setData([]);
      setTotal(0);
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchData(params);
  }, [deviceCode, deviceType, areaId, params]);

  const handleTableChange = (pagination: { current: number; pageSize: number }) => {
    setParams((prevParams) => ({
      ...prevParams,
      current: pagination.current,
      pageSize: pagination.pageSize,
    }));
  };

  const handleSearch = (values: any) => {
    const startDate = dayjs(values.startDate);
    const endDate = dayjs(values.endDate);
    if (endDate.diff(startDate, 'day') > 31) {
      message.warning(intl.formatMessage({ id: 'data.sDays' }));
      return;
    }
    setParams((prevParams) => ({
      ...prevParams,
      startDate: values.startDate,
      endDate: values.endDate,
    }));
  };

  const handleReset = () => {
    setParams({
      current: 1,
      pageSize: 20,
      startDate: dayjs().startOf('day').format('YYYY-MM-DDTHH:mm:ss'),
      endDate: dayjs().format('YYYY-MM-DDTHH:mm:ss'),
    });
    fetchData(params);
  };

  const scroll = {
    x: 'max-content',
    y: 'calc(100vh - 300px)',
  };

  const columnToAttrMap: Record<string, string> = {
    time: 'ts',
    faultCount: 'faultNum',
    soc: 'soc',
    dailyCharge: 'todayChargedEnergy',
    dailyDischarge: 'todayDischargedEnergy',
    totalCharge: 'chargedEnergy',
    totalDischarge: 'dischargedEnergy',
  };

  const exportDataReportFun = async (params: any) => {
    const startDate = dayjs(params.startDate);
    const endDate = dayjs(params.endDate);
    if (endDate.diff(startDate, 'day') > 3) {
      message.warning(intl.formatMessage({ id: 'data.selectTimeRange' }));
      return;
    }

    const attrNames =
      selectedColumns.length > 0
        ? selectedColumns
            .filter((col) => col !== 'index' && col !== 'pageIndex')
            .map((col) => columnToAttrMap[col] || col)
        : Object.values(columnToAttrMap);

    const exportParams: API.HistoryDataQuery = {
      areaId: Number(areaId),
      deviceType,
      deviceCode,
      startDate: dayjs(params.startDate).format('YYYY-MM-DD HH:mm:ss'),
      endDate: dayjs(params.endDate).format('YYYY-MM-DD HH:mm:ss'),
      attrNames,
    };
    await downloadFetch(exportDataReport, exportParams);
  };

  return (
    <div>
      <ProTable
        headerTitle={intl.formatMessage({ id: 'data.batteryBoxDetails' })} // 使用国际化字段
        search={{
          labelWidth: 80,
        }}
        columns={columns}
        scroll={scroll}
        pagination={{
          current: params.current,
          pageSize: params.pageSize,
          total,
          onChange: (page, pageSize) => handleTableChange({ current: page, pageSize }),
        }}
        dataSource={data}
        loading={loading}
        onSubmit={handleSearch}
        onReset={handleReset}
        columnsState={{
          value: Object.fromEntries(
            columns
              .filter((col) => col.dataIndex)
              .map((col) => [
                col.dataIndex,
                {
                  show:
                    selectedColumns.length === 0
                      ? true
                      : selectedColumns.includes(col.dataIndex as string),
                },
              ]),
          ),
          onChange: (stateMap) => {
            const newSelectedColumns = Object.entries(stateMap)
              // eslint-disable-next-line @typescript-eslint/no-unused-vars
              .filter(([_, value]) => value.show)
              .map(([key]) => key);
            setSelectedColumns(newSelectedColumns);
          },
        }}
        toolbar={{
          className: 'historyToobalr',
          actions: [
            <>
              <HandleBtn
                key="export"
                handleType="export"
                onClick={() => exportDataReportFun(params)}
              >
                {intl.formatMessage({ id: 'statistics.common.export' })}
              </HandleBtn>
              <Link key="monitor" to={`/stationmonitor/realtime?key=${selectedKeys}`}>
                {intl.formatMessage({ id: 'data.realtimeMonitor' })}
              </Link>
            </>,
          ],
        }}
      />
    </div>
  );
};

export default BatteryBoxDetails;
